import { AppDataSource } from '../config/database';
import { User } from '../entities/User';
import { Repository } from 'typeorm';
import bcrypt from 'bcryptjs';
import jwt from 'jsonwebtoken';


export class UserService {
  private userRepository: Repository<User>;

  constructor() {
    this.userRepository = AppDataSource.getRepository(User);
  }

  // 注册
  async register(account: string, password: string, email: string = '') {
    
    // 检查用户名是否已存在
    const existingUser = await this.userRepository.findOne({ where: { account } });
    if (existingUser) {
      throw new Error('该用户已存在');
    }

    // 检查邮箱是否已存在
    // const existingEmail = await this.userRepository.findOne({ where: { email } });
    // if (existingEmail) {
    //   throw new Error('邮箱已被注册');
    // }

    // 加密密码
    const hashedPassword = await bcrypt.hash(password, 10);

    // 创建新用户
    const user = this.userRepository.create({
      account,
      password: hashedPassword,
      email
    });

    await this.userRepository.save(user);
    return user;
  }

  // 登录
  async login(account: string, password: string) {
    const user = await this.userRepository.findOne({ where: { account } });
    
    if (!user) {
      throw new Error('用户不存在');
    }

    const isValidPassword = await bcrypt.compare(password, user.password);
    if (!isValidPassword) {
      throw new Error('密码错误');
    }

    // 生成 JWT token
    const token = jwt.sign(
      { userId: user.id, account: user.account },
      process.env.JWT_SECRET || 'your-secret-key',
      { expiresIn: '24h' }
    );

    return token
  }

  // 获取用户信息
  async getUserInfo(userId: number) {
    const user = await this.userRepository.findOne({ where: { id: userId } });
    if (!user) {
      throw new Error('用户不存在');
    }

    return {
      id: user.id,
      account: user.account,
      email: user.email,
      avatar: user.avatar,
      nickname: user.nickname,
      gender: user.gender,
      birthday: user.birthday
    };
  }

  // 获取用户列表（分页）
  async getUserList(pageNo: number = 1, pageSize: number = 10) {
    const skip = (pageNo - 1) * pageSize;
    const [users, total] = await this.userRepository.findAndCount({
      select: {
        id: true,
        account: true,
        email: true,
        avatar: true,
        nickname: true,
        gender: true,
        birthday: true,
        createdAt: true,
        status: true
      },
      skip,
      take: pageSize,
      order: {
        createdAt: 'DESC'
      }
    });

    return {
      list: users,
      total,
      pageNo,
      pageSize,
      totalPages: Math.ceil(total / pageSize)
    };
  }

} 